//
//  CXTextView.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/27.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

@IBDesignable class CXTextView: UITextView {

    /// 自定义一个占位字符的属性; 加上关键字方便在xib sb的右边栏进行设置
    @IBInspectable var placeholder: String? {
        
        didSet {
            placeholderView.text = placeholder
        }
    }
    /// 当给当前text视图赋值内容或者在xib边栏的属性框里敲字时 是否隐藏 placeholderView
    @IBInspectable override var text: String? {
        
        didSet {
            placeholderView.hidden = self.hasText()
        }
    }
    /// 设置占位视图的字体类型
    override var font: UIFont? {
        
        didSet {
            placeholderView.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    /// 占位文字视图
    private lazy var placeholderView: UILabel = {
       
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.grayColor()
        label.numberOfLines = 0 //可以多行显示
        return label
    }()

    ///  布局placeholderView
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //让占位符区域的位置与系统默认输入的文字的位置一致
        placeholderView.frame.origin.y = 8
        placeholderView.frame.origin.x = 5
        
        let maxsize = CGSize(width: self.frame.width - 2 * placeholderView.frame.origin.x, height: CGFloat(MAXFLOAT))
        
        /// 检查占位区域是否有内容
        guard let textStr = placeholderView.text else {
            return
        }
        
        let textsize = (textStr as NSString).boundingRectWithSize(maxsize, options: [.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: placeholderView.font], context: nil).size
        //通过文字计算尺寸
        placeholderView.frame.size = textsize
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
// MARK: - 设置UI
extension CXTextView {
    
    private func setupUI() {
        
        addSubview(placeholderView)
        ///  在通过键盘给当前view输入文字时 监听这个事件 然后对之做处理
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange:", name: UITextViewTextDidChangeNotification, object: self)
        
    }
    ///  当在界面上向里面敲字时 调用该方法
    @objc private func textDidChange(noti: NSNotification) {
        placeholderView.hidden = self.hasText()
    }
    
}